import defaultGif from '../assets/default.gif';
import $bus from '../eventBus.js';
import debounce from '../utils/debounce.js';


var imgs = [];
// 滚动条滚动，加载合适的图片
function setImage(img) {
    img.dom.src = defaultGif;//一开始都是加载的图片格式
    // 判断符合视口内的图片
    var distance = img.dom.getBoundingClientRect();
    var clientHeight = document.documentElement.clientHeight;//视口高度
    if (distance.top >= -150 && distance.top <= clientHeight) {
        img.dom.src = img.src;
    }
}
function setImages() {
    for (const img of imgs) {//看每张图片是否在视口内进行处理
        setImage(img)
    }
}

function handle() {
    setImages();
}
$bus.$on('mainScroll', debounce(handle, 50));//滚动条防抖处理




export default {
    inserted(el, bindings) {//元素放入父级就存储img
        var img = {
            dom: el,
            src: bindings.value,
        };
        imgs.push(img)
        setImage(img)
    },
    unbind(el) {//元素消失的时候就从imgs里删除
        imgs = imgs.filter((item) => {
            return item.dom !== el;
        })
    }
}